﻿using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WD.Shell.Zoom
{
    public class MagnificationHelper
    {
        private readonly Ellipse _magnifierEllipse;
        private readonly Canvas _graphControl;
        private readonly Canvas _magnifierCanvas;
        private readonly Slider _uiScaleSlider;

        public MagnificationHelper(Canvas graphControl, Ellipse magnifierEllipse, Canvas magnifierCanvas, Slider uiScaleSlider)
        {
            _uiScaleSlider = uiScaleSlider;
            _uiScaleSlider.ValueChanged += UiScaleSliderValueChanged;
            var b = (VisualBrush)magnifierEllipse.Fill;
            b.Visual = graphControl;
            _magnifierCanvas = magnifierCanvas;
            _graphControl = graphControl;
            _magnifierEllipse = magnifierEllipse;
            graphControl.PreviewMouseMove += GraphControlPreviewMouseMove;
        }

        /// <summary>
        /// Slider value changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UiScaleSliderValueChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
        {
            var newValue = e.NewValue;
            ZoomChanged(newValue);
        }

        /// <summary>
        /// Handle mouse move
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void GraphControlPreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            var b = (VisualBrush)_magnifierEllipse.Fill;
            var pos = e.MouseDevice.GetPosition(_graphControl);
            var viewBox = b.Viewbox;
            double xoffset = viewBox.Width / 2.0;
            double yoffset = viewBox.Height / 2.0;
            viewBox.X = pos.X - xoffset;
            viewBox.Y = pos.Y - yoffset;
            b.Viewbox = viewBox;
            Canvas.SetLeft(_magnifierCanvas, pos.X - _magnifierEllipse.Width / 2);
            Canvas.SetTop(_magnifierCanvas, pos.Y - _magnifierEllipse.Height / 2);
        }

        /// <summary>
        /// handle slider zoom changed event
        /// </summary>
        /// <param name="val"></param>

        private void ZoomChanged(double val)
        {
            if (_magnifierEllipse != null)
            {
                var b = (VisualBrush)_magnifierEllipse.Fill;
                var viewBox = b.Viewbox;
                viewBox.Width = val;
                viewBox.Height = val;
                b.Viewbox = viewBox;
            }
        }
    }
}
